package cn.tedu.coolshark12.controller;

import cn.tedu.coolshark12.entity.Product;
import cn.tedu.coolshark12.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;

    //添加商品
    @RequestMapping("product/insert")
    public void insert( @RequestBody Product product){
        System.out.println("product = " + product);
        //设置商品的发布时间为当前系统时间
        product.setCreated(new Date());
        //调用mapper的insert方法
        mapper.insert(product);
    }

    //查询商品
    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    //删除商品
    @RequestMapping("/product/delete")
    public void delete(int id){
        //通过ID查询到商品的路径
        String url =mapper.selectUrlById(id);
        String filePath ="D:/files/"+url;
        new File(filePath).delete();
        mapper.deleteById(id);
    }

    //首页展示商品
    @RequestMapping("/product/select/index")
    public List<Product> selectIndex(){
        return mapper.selectIndex();
    }
}
